package agency.tango.materialintroscreen.listeners.scrollListeners;

import agency.tango.materialintroscreen.SlideComponentContainer;
import org.jetbrains.annotations.Nullable;

import agency.tango.materialintroscreen.adapter.SlidesAdapter;
import agency.tango.materialintroscreen.listeners.IPageScrolledListener;
import agency.tango.materialintroscreen.parallax.Parallaxable;
import agency.tango.materialintroscreen.SlideViewBuilder;

/**
 * @ProjectName: material-intro-screen-master
 * @Package: agency.tango.materialintroscreen.listeners.scrollListeners
 * @ClassName: ParallaxScrollListener
 * @Description: pageslider滑动监听器实现类
 * @CreateDate: 2021/4/12 16:43
 * @UpdateDate: 2021/4/12 16:43
 * @UpdateRemark: 暂无
 * @Version: 1.0
 */
public class ParallaxScrollListener implements IPageScrolledListener {
    private SlidesAdapter adapter;

    public ParallaxScrollListener(SlidesAdapter adapter) {
        this.adapter = adapter;
    }

    @Override
    public void pageScrolled(int position, float offset) {
        if (adapter == null) {
            return;
        }
        if (position != adapter.getCount()) {
            SlideComponentContainer view = adapter.getItem(position);
            SlideComponentContainer fragmentNext = getNextFragment(position);
            if (view instanceof Parallaxable) {
                ((Parallaxable) view).setOffset(offset);
            }
            if (fragmentNext != null && view instanceof Parallaxable) {
                ((Parallaxable) fragmentNext).setOffset(offset - 1);
            }
        }
    }

    @Nullable
    private SlideComponentContainer getNextFragment(int position) {
        if (adapter == null) {
            return new SlideViewBuilder().build(null);
        }
        if (position < adapter.getLastItemPosition()) {
            return adapter.getItem(position + 1);
        }
        return new SlideViewBuilder().build(null);
    }
}